<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/15 18:35
 * Note: 登录、修改密码
 */
namespace Admin\Controller;
use Think\Controller;
class PublicController extends CommonController {

    /**
     * 后台登录
     * @author jlb <[<email address>]>
     * @return [type] [description]
     */
    public function index(){
        if($_SESSION['SESSION_PREFIX']['adminInfo']){
            $this->redirect("Index/index");
        }
        $this->display('login');
    }

    public function login(){
        if ( !IS_POST )
        {
            $this->error('非法请求','index');
        }

        $uname = I('post.username', '', 'trim');
        $pword = I('post.pwd', '', 'trim');

        if ( !$uname )
        {
            $this->error('请输入账号');
        }
        if ( !$pword ) {
            $this->error('请输入密码');
        }
        $whereLogin['username'] = $uname;
        $whereLogin['password'] = md5($pword);

        $result = M('User')->where($whereLogin)->find();

        if($result){
            session('adminInfo', $result);
            //保存登录信息
            $data['id'] = $result['id'];    //用户ID
            $data['login_ip'] = get_client_ip();    //最后登录IP
            $data['login_time'] = time();       //最后登录时间
            $data['login_count'] = $result['login_count'] + 1;
            M('User')->save($data);
            $this->success('验证成功，正在跳转到首页',U('Index/index'));
        }else{
            $this->error('账户或密码错误');
        }
    }

    /**
     * 退出登录
     * @return [type] [description]
     */
    public function logout(){
        unset($_SESSION);
        session_destroy();
        $this->assign("jumpUrl",U('Public/index'));
        $this->success('安全退出！');
    }

    //修改密码
    public function pwd(){
        $info = M('User')->where("id=1")->find();
        $info['updatetime'] = date('Y-m-d H:i:s', $info['updatetime']);
        if(IS_POST){
            $id = I('id',1,'intval');
            $password = I('post.password','','trim');
            $repassword = I('post.repassword','','trim');
            if($password !== $repassword){
                $this->error('两次输入的密码不一致，请重新输入！',U('Public/pwd'),3);
            }
            $password = md5($password);
            $data = array(
                'id' => $id,
                'password' => $password,
                'updatetime' => time(),
            );
            $result = M('User')->save($data);
            if($result) {
                $this->success('更新成功！',U('Index/index'));
            }else{
                $this->error('更新失败！',U('Index/index'));
            }
            return;
        }
//        print_r($info);die();
        $this->assign('info', $info);
        $this->assign('title', '修改密码');
        $this->display();
    }
	
	//清理缓存
    public function clearcache()
    {
        $dir = "./Application/Runtime/Cache";
        $rtim=del_dir($dir);
        if($rtim){
            $this->success('清除成功');
        }else{
            $this->error('清除失败');
        }
    }
}